package com.bugsnag.ohos;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * Unroll the list of causes for this Throwable, handling any recursion that may appear within
 * the chain. The first element returned will be this Throwable, and the last will be the root
 * cause or last non-recursive Throwable.
 *
 * @since 2021-07-01
 */
public class ThrowableUtils {
    private ThrowableUtils() {
    }

    /**
     * safe Unroll Causes
     *
     * @param throwable
     * @return causes
     */
    public static List<Throwable> safeUnrollCauses(Throwable throwable) {
        LinkedHashSet causes = new LinkedHashSet<Throwable>();
        Throwable currentEx = throwable;
        while (currentEx != null && causes.add(currentEx)) {
            currentEx = currentEx.getCause();
        }
        Iterator<Throwable> iterator = causes.iterator();
        List<Throwable> list = new ArrayList<>();
        while (iterator.hasNext()) {
            list.add(iterator.next());
        }
        return list;
    }
}
